<template>
    <div class="tree_table">
        <SplitPane>
            <template v-slot:left>
                <div class="splitpane_left">
                    <div class="splitpane-tree">
                        <div class="splitpane-tree-title flex_between">
                            <div>字典类型</div>
                            <div class="splitpane-tree-operate">
                                <el-button-group class="tree_button_grounp">
                                    <el-tooltip content="新增" :open-delay="500">
                                        <el-button type="primary" link :icon="CirclePlus" circle
                                            @click="addDictType"></el-button>
                                    </el-tooltip>
                                </el-button-group>
                            </div>
                        </div>
                        <div class="splitpane-tree-content">
                            <el-input clearable placeholder="输入关键字" v-model="filterText" prefix-icon="el-icon-search">
                            </el-input>
                            <div class="tree_main_content">
                                <el-tree v-loading="treeLoading" :expand-on-click-node="false" :indent="24"
                                    :filter-node-method="filterNode" default-expand-all class="filter-tree"
                                    :data="treeData" :node-key="nodeKey" :props="defaultProps" ref="treeRef"
                                    @node-click="handleNodeClick" :current-node-key="currentNodekey" highlight-current>
                                    <template #default="{ node, data }">
                                        <div class="splitpane-tree-node">
                                            <span :title="node.label">{{ node.label }}</span>
                                            <span class="el-button-groups">
                                                <el-button-group class="tree_button_grounp">
                                                    <el-tooltip :open-delay="500" content="编辑">
                                                        <el-button :icon="Edit" type="primary" link
                                                            @click="editTree(data)"></el-button>
                                                    </el-tooltip>
                                                    <el-tooltip :open-delay="500" content="删除">
                                                        <el-button :icon="Delete" class="g-red" type="primary" link
                                                            @click="removeTreeById(data)"></el-button>
                                                    </el-tooltip>
                                                </el-button-group>
                                            </span>
                                        </div>
                                    </template>
                                </el-tree>
                            </div>
                        </div>
                    </div>
                </div>

            </template>
            <template v-slot:right>
                <div class="splitpane_right">
                    <div class="single-table-container">
                        <div class="search-form-wrapper">
                            <div class="title">字典数据列表</div>
                            <div class="seach_list">
                                <el-input :prefix-icon="Search" placeholder="请输入名称/值" v-model="searchForm.query"
                                    clearable></el-input>
                                <el-button type="primary"  @click="refreshTable">查询</el-button>
                                <el-button type="primary" plain @click="addDictData">新增</el-button>
                                <el-button type="primary" plain @click="refreshCache">刷新缓存</el-button>
                                <el-button type="danger"  @click="removeBatch">批量删除</el-button>
                            </div>
                        </div>
                        <div class="single-table">
                            <el-table ref="tableRef" v-loading="tableLoading" height="100%" :data="tableData" stripe
                                tooltip-effect="dark" :header-cell-style="headerCellStyle" :border="true">
                                <el-table-column type="selection" width="50" align="center"></el-table-column>
                                <el-table-column prop="dictCode" label="字典类型" show-overflow-tooltip
                                    :formatter="formartEmpty"></el-table-column>
                                <el-table-column prop="dictLabel" label="名称" show-overflow-tooltip
                                    :formatter="formartEmpty"></el-table-column>
                                <el-table-column prop="dictValue" label="值" show-overflow-tooltip
                                    :formatter="formartEmpty"></el-table-column>
                                <el-table-column prop="remark" label="备注" show-overflow-tooltip
                                    :formatter="formartEmpty"></el-table-column>
                                <el-table-column prop="sort" label="序号" show-overflow-tooltip></el-table-column>
                                <el-table-column width="120" label="操作" header-align="center" align="center">
                                    <template #default="scope">
                                        <div class="flex">
                                            <el-button type="primary" link @click="updateDictData(scope.row)">编辑</el-button>
                                            <el-button type="primary" link class="g-red"
                                                @click="removeById(scope.row)">删除</el-button>
                                        </div>

                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="table-pagination">
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                background :current-page="pages.pageIndex" :page-sizes="pages.pageSizeList"
                                :page-size="pages.pageSize" layout="total, sizes, prev, pager, next, jumper"
                                :total="pages.total"></el-pagination>
                        </div>
                    </div>
                </div>
            </template>
        </SplitPane>
        <addOrEditDictType ref="addOrEditDictTypeRef" @callback="initData"></addOrEditDictType>
        <addOrEditDictData ref="addOrEditDictDataRef" @callback="getTableData"></addOrEditDictData>
    </div>
</template>
<script setup lang="ts" name="sysDict">
import addOrEditDictType from "./_compoents/addOrEditDictType.vue";
import addOrEditDictData from "./_compoents/addOrEditDictData.vue";
import { CirclePlus, Search, Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref, watch, nextTick } from 'vue'
import { ElTree, ElMessageBox, ElMessage, ElTable } from 'element-plus'
import { getDictTypeTree, getDictDataByPage, deleteSysDictTypeById, deleteDictDataById, deleteBatchDictData, refreshDictCache } from "@/api/sys/dictApi";
import { formartEmpty } from "@/utils";
const addOrEditDictTypeRef = ref(addOrEditDictType);
const addOrEditDictDataRef = ref(addOrEditDictData);
interface Tree {
    [key: string]: any
}
// tree
const nodeKey = 'id'
const currentNodekey = ref('')
const treeLoading = ref(false)
const defaultProps = {
    children: 'children',
    label: 'dictName'
}
const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<Tree[]>([])
//table
const headerCellStyle = {
    background: '#f5f7fa',
    fontWeight: 'bold',
    color: '#303133'
}
const searchForm = ref({
    query: '',
});
const tableLoading = ref(false)
const tableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref([]);
const pages = ref({
    pageIndex: 1,
    pageSize: 10,
    pageSizeList: [10, 20, 30, 50, 100],
    total: 0
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.dictName.includes(value)
}

const handleNodeClick = (data: Tree) => {
    currentNodekey.value = data.id
}
const initData = () => {
    getDeptTreeData();
}

const getDeptTreeData = async () => {
    treeLoading.value = true
    setTimeout(() => {
        treeLoading.value = false;
    }, 5000);
    const res = await getDictTypeTree();
    if (res.code == 200) {
        treeData.value = res.result;
        nextTick(() => {
            currentNodekey.value = res.result[0].id
        })
    }
    treeLoading.value = false;
}
const addDictType = () => {
    addOrEditDictTypeRef.value.openLoad("add")
}
const editTree = (node: Tree) => {
    addOrEditDictTypeRef.value.openLoad("update", node)
}
const removeTreeById = (node: Tree) => {
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        await deleteTreeAction(node);
    })
}
const deleteTreeAction = async (data: Tree) => {
    const id = data.id;
    treeLoading.value = true;
    const res: apiServerResponse = await deleteSysDictTypeById(id)
    if (res.code == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        initData();
    }
    treeLoading.value = false;
}
// table 方法
const refreshTable = () => {
    pages.value.pageIndex = 1;
    getTableData();
}
const getTableData = async () => {
    tableLoading.value = true
    setTimeout(() => {
        tableLoading.value = false;
    }, 5000);
    const params: SysDictDataEntityRequestParams = {
        current: pages.value.pageIndex,
        size: pages.value.pageSize,
        dictTypeId: currentNodekey.value,
        ...searchForm.value
    }
    const res = await getDictDataByPage(params);
    if (res.code == 200) {
        tableData.value = res.result.records;
        pages.value.total = res.result.total;
    }
    tableLoading.value = false;
}
const addDictData = () => {
    const data = {
        dictTypeId: currentNodekey.value,
        dictCode: treeRef.value!.getCurrentNode().dictCode,
    }
    addOrEditDictDataRef.value.openLoad("add", data)
}

const updateDictData = (row: any) => {
    addOrEditDictDataRef.value.openLoad("update", row)
}
const removeById = (row: any) => {
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        await deleteTableByIdAction(row.id);
    })
}
const removeBatch = () => {
    const ids = tableRef.value!.getSelectionRows().map((item: any) => item.id);
    if (ids && ids.length > 0) {
        ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            await deleteBatchTableAction(ids);
        })
    } else {
        ElMessage({
            message: '请选择要删除的数据',
            type: 'warning',
        })
    }

}
const deleteTableByIdAction = async (id: string) => {
    const res: apiServerResponse = await deleteDictDataById(id)
    if (res.code == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        getTableData();
    }
}

const deleteBatchTableAction = async (ids: string[]) => {
    const res: apiServerResponse = await deleteBatchDictData(ids)
    if (res.code == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        getTableData();
    }
}
const refreshCache = () => {
    refreshDictCache().then((res: apiServerResponse) => {
        if (res.code == 200) {
            ElMessage({
                message: '刷新缓存成功',
                type: 'success',
                duration: 1000
            })
        }
    })

}

// 监听
const handleCurrentChange = (val: number) => {
    pages.value.pageIndex = val;
    getTableData();
}
const handleSizeChange = (val: number) => {
    pages.value.pageSize = val;
    getTableData();
}


watch(filterText, (val) => {
    treeRef.value!.filter(val)
})
watch(currentNodekey, (val) => {
    if (val) {
        getTableData();
    }
})

onMounted(() => {
    initData();
})
</script>
<style lang="scss" scoped>
.tree_table {
    height: 100%;
    padding: 10px;
    width: 100%;
    box-sizing: border-box;

    .single-table-container {
        padding: 0;
    }
}

.moreSelect {
    :deep(.el-form-item__label) {
        color: #303133;
    }

    .el-date-editor--datetimerange.el-input,
    .el-date-editor--datetimerange.el-input__inner {
        width: 100%;
    }

    .el-select {
        width: 100%;
    }
}
</style>